<template>
  <el-form :model="nodeModalForm"
           ref="nodeModal"
           label-placement="left"
           label-width="120px"
           :rules="nodeModalRules"
           size="small">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="节点名称"
                      prop="nodeName">
          <el-input v-model.trim="nodeModalForm.nodeName"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <table border="1"
           align="center"
           class="add_table w_100"
           cellspacing="0">
      <tr>
        <th width="70"><span class="iconfont icon-Add cursor_point"
                @click="handleAddCompute"></span></th>
        <th>选择列</th>
        <th>运算符</th>
        <th>选择列</th>
        <th>列别名</th>
        <th>删除原有列</th>
      </tr>
      <tr v-for="(compute,index) in nodeModalForm.computes"
          :key="index">
        <td width="70">
          <span class="iconfont icon-Add cursor_point px_2"
                @click="handleAddCompute(index)"></span>
          <span class="iconfont icon-close cursor_point px_2"
                @click="handleDeleteCompute(index)"></span>
        </td>
        <td>
          <el-select v-model="compute.first"
                     clearable
                     filterable
                     placeholder="运算符"
                     class="fixed-icon w_100">
            <el-option v-for="numeric in numericList"
                       :key="numeric.alias"
                       :label="numeric.alias"
                       :value="numeric.alias">
              <span style="float: left">{{ numeric.alias }}</span>
              <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">{{
                  numeric.DATA_TYPE
                }}</span>
            </el-option>
          </el-select>
        </td>
        <td>
          <el-select v-model="compute.function"
                     clearable
                     filterable
                     placeholder="条件"
                     class="fixed-icon w_100">
            <el-option v-for="func in operationList"
                       :key="func.value"
                       :label="func.label"
                       :value="func.value"></el-option>
          </el-select>
        </td>
        <td>
          <el-select v-model="compute.last"
                     clearable
                     filterable
                     placeholder="选择列"
                     class="fixed-icon w_100">
            <el-option v-for="numeric in numericList"
                       :key="numeric.alias"
                       :label="numeric.alias"
                       :value="numeric.alias">
              <span style="float: left">{{ numeric.alias }}</span>
              <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">{{
                  numeric.DATA_TYPE
                }}</span>
            </el-option>
          </el-select>
        </td>
        <td>
          <el-input v-model.trim="compute.alias"
                    clearable
                    placeholder="列别名"></el-input>
        </td>
        <td align="center">
          <el-checkbox v-model="compute.deleteColumn"
                       size="small"
                       label="删除原有列"></el-checkbox>
        </td>
      </tr>
    </table>
    <div class="nodeModal-footer">
      <span class="dialog-footer">
        <el-button plain
                   @click="handleConfigCancel">取消</el-button>
        <el-button type="primary"
                   @click="handleConfigConfirm">更新</el-button>
      </span>
    </div>
  </el-form>
</template>

<script>
import { computed, defineComponent, inject, onMounted, ref } from 'vue'
import { separatorList } from '../../../../../utils/dict'
import { useEtlStore } from '../../../../../store/flowEtl'
import { numberType } from '../../../../../utils/constant'
import { cloneDeep } from 'lodash-es'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'node-config-computes',
  props: {
    node: Object,
  },
  components: {},
  setup(props, ctx) {
    const etlStore = useEtlStore()
    const nodeList = computed(() => etlStore.nodeList)
    const rowsList = ref([])
    const numericList = ref([])
    const operationList = ref([
      {
        label: '加',
        value: '+',
      },
      {
        label: '减',
        value: '-',
      },
      {
        label: '乘',
        value: '*',
      },
      {
        label: '除',
        value: '/',
      },
    ])
    const nodeConfigClose = inject('nodeConfigClose')
    const nodeModalForm = ref({
      nodeName: '',
      fields: '',
      computes: [],
    })
    const nodeModal = ref()
    const nodeModalRules = ref({
      nodeName: {
        required: true,
        message: '请输入数据源名称',
        trigger: 'blur',
      },
    })
    const handleConfigCancel = () => {
      nodeConfigClose()
    }
    const nodeConfigUpdate = (node) => {
      let columns = []
      let emptyFlag = false
      columns = cloneDeep(props.node.originFields)
      node.computes.map((compute) => {
        if (compute.deleteColumn) {
          if (!compute.first || !compute.last || !compute.alias) {
            emptyFlag = true
          }
          let firstIndex = columns.findIndex((column) => {
            return column.alias == compute.first
          })
          if (firstIndex >= 0) {
            columns.splice(firstIndex, 1)
          }
          let lastIndex = columns.findIndex((column) => {
            return column.alias == compute.last
          })
          if (lastIndex >= 0) {
            columns.splice(lastIndex, 1)
          }
        }
        columns.push({
          COLUMN_COMMENT: compute.alias,
          COLUMN_NAME: compute.alias,
          DATA_TYPE: 'numeric',
          alias: compute.alias,
        })
      })
      if (emptyFlag) {
        ElMessage.error('请填写完整信息！！！')
        return
      }
      let aliasColumns = columns.map((item) => item.alias)
      let repeatAlias = []
      aliasColumns.forEach((alias) => {
        let len = aliasColumns.filter((item) => item === alias).length
        if (len > 1) {
          repeatAlias.push(alias)
        }
      })
      if (repeatAlias.length) {
        ElMessage.error(`存在相同的别名(${repeatAlias.join(',')}),请修改`)
        return
      }
      let nodes = [...nodeList.value].map((item) => {
        if (item.id === node.id) {
          item.status = true
          item.nodeName = node.nodeName
          item.config.rowName = node.rowName
          item.config.computes = node.computes
          item.config.fields = columns
        }
        return item
      })
      etlStore.setNodeList(nodes)
      nodeConfigClose()
    }
    const handleConfigConfirm = () => {
      nodeModal.value.validate((valid) => {
        if (valid) {
          nodeConfigUpdate(nodeModalForm.value)
        } else {
          return false
        }
      })
    }
    const resetForm = () => {
      nodeModalForm.value = {
        id: null,
        nodeName: '',
        computes: [],
        fields: [],
      }
    }
    const handleAddCompute = (index) => {
      if (index) {
        nodeModalForm.value.computes = [
          ...nodeModalForm.value.computes.splice(0, index + 1),
          {
            first: '',
            function: '+',
            last: '',
            alias: '',
            deleteColumn: false,
          },
          ...nodeModalForm.value.computes.splice(
            index - 1,
            nodeModalForm.value.computes.length
          ),
        ]
      } else {
        nodeModalForm.value.computes.push({
          first: '',
          function: '+',
          last: '',
          alias: '',
          deleteColumn: false,
        })
      }
    }
    const handleDeleteCompute = (index) => {
      nodeModalForm.value.computes.splice(index, 1)
    }
    onMounted(() => {
      resetForm()
      nodeModalForm.value = {
        id: props.node.id,
        nodeName: props.node.nodeName,
        computes: props.node.config.computes || [],
        fields: props.node.config.fields || [],
      }
      rowsList.value = props.node.originFields
      numericList.value = props.node.originFields.filter((field) => {
        let type = field.DATA_TYPE
        let regType = type.replace(/[0-9]+/g, '')
        if (numberType.includes(regType)) {
          return field
        }
      })
    })
    return {
      separatorList: separatorList,
      rowsList,
      numericList,
      nodeList,
      nodeModalForm,
      nodeModalRules,
      nodeModal,
      operationList,
      resetForm,
      handleConfigCancel,
      handleConfigConfirm,
      nodeConfigUpdate,
      nodeConfigClose,
      handleAddCompute,
      handleDeleteCompute,
    }
  },
})
</script>

<style scoped>
.field-table {
  padding: 0 12px 24px;
}

.nodeModal-footer {
  padding: var(--el-dialog-padding-primary);
  padding-top: 10px;
  text-align: right;
  box-sizing: border-box;
}
</style>